package com.platform.modules.app.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.platform.annotation.LoginUser;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.*;
import com.platform.modules.app.entity.BuyGoodsVo;
import com.platform.modules.mall.activity.entity.bo.DirectGoShoppingBo;
import com.platform.modules.mall.activity.service.GoShoppingService;
import com.platform.modules.mall.entity.*;
import com.platform.modules.mall.service.*;
import com.platform.modules.order.IOrderBuildSelect;
import com.platform.modules.order.OrderBootstrap;
import com.platform.modules.sys.service.SysConfigService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;


/**
 * @author
 */
@RestController
@RequestMapping("/app/buy")
@Api(tags = "AppBuyController|商品购买")
@Slf4j
public class AppBuyController {
    @Autowired
    JedisUtil jedisUtil;
    @Autowired
    private MallGoodsService goodsService;
    @Autowired
    private MallCardSnService snService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private MallOrderService orderService;
    @Autowired
    private MallOrderGoodsService orderGoodsService;
    @Autowired
    private MallActivityService activityService;
    @Autowired
    private MallGoodsToActivityService goodsToActivityService;

    @Autowired
    MallWhitelistService whitelistService;

    @Autowired
    MallUserActivityMobileService userActivityMobileService;
    @Autowired
    SysConfigService configService;


    @ApiOperation(value = "商品添加")
    @PostMapping("/add")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", name = "jsonParam", value = "JSON格式参数", examples = @Example({
                    @ExampleProperty(mediaType = "goodsId", value = "goodsId"),
                    @ExampleProperty(mediaType = "number", value = "1")
            }), required = true, dataType = "string")
    })
    public Object addBuy(@LoginUser MallUserEntity loginUser, @RequestBody JSONObject jsonParam) {
        String skuId = jsonParam.getString("skuId");
        String goodsId = jsonParam.getString("goodsId");
        Integer number = jsonParam.getInteger("number");

        jedisUtil.del(Constant.MTM_CACHE + "goods" + loginUser.getId());
        BuyGoodsVo goodsVo = new BuyGoodsVo();
        goodsVo.setGoodsId(goodsId);
        goodsVo.setNumber(number);
        goodsVo.setSkuId(skuId);
        jedisUtil.setObject(Constant.MTM_CACHE + "goods" + loginUser.getId(), goodsVo);
        return RestResponse.success("添加成功");
    }

    /**
     * 三六活动提交订单
     */
    @PostMapping("acticitySubmitOrder")
    @ApiOperation(value = "提交订单", notes = "购物车页面提交订单，商品为购物车中已经选中的")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "token", value = "用户token", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "body", name = "jsonParam", value = "JSON格式参数", examples = @Example({
                    @ExampleProperty(mediaType = "fromType", value = "用户下单来源类型 1:微信小程序 2:微信公众号 3:app 4:H5 5:支付宝小程序 6:QQ小程序"),
                    @ExampleProperty(mediaType = "goodsId", value = "商品id"),
                    @ExampleProperty(mediaType = "activityId", value = "活动id"),
                    @ExampleProperty(mediaType = "type", value = "类型"),
                    @ExampleProperty(mediaType = "mobile", value = "手机"),
                    @ExampleProperty(mediaType = "number", value = "数量")
            }), required = true, dataType = "string")
    })
    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_UNCOMMITTED)
    public RestResponse acticitySubmitOrder(@LoginUser MallUserEntity loginUser, @RequestBody JSONObject jsonParam) {

        String postscript = jsonParam.getString("postscript");
        Integer fromType = jsonParam.getInteger("fromType");
        String goodsId = jsonParam.getString("goodsId");
        Integer number = jsonParam.getInteger("number");
        String shopsId = jsonParam.getString("shopsId");
        String activityId = jsonParam.getString("activityId");
        String skuId = jsonParam.getString("skuId");
//        Integer type = jsonParam.getInteger("type");
//        String mobile = loginUser.getMobile();
        MallActivityEntity activityEntity = activityService.getById(activityId);
        String mobile = "";


//        String code = jsonParam.getString("code");

        if (number == null || StringUtils.isBlank(goodsId) || fromType == null) {
            return RestResponse.error("参数错误！");
        }
        MallGoodsEntity entity = goodsService.getById(goodsId);
        if (!org.apache.commons.lang3.ObjectUtils.allNotNull(entity)) {
            return RestResponse.error("商品不存在！");
        }
        if (entity.getIsLimited() > 0 && entity.getIsLimited() < number) {
            throw new BusinessException("超出限购数量！");
        }

        // 判断是否为活动商品
        List<MallGoodsToActivityEntity> goodsToActivityEntities = goodsToActivityService.lambdaQuery()
                .select(MallGoodsToActivityEntity::getActivityId, MallGoodsToActivityEntity::getId)
                .eq(MallGoodsToActivityEntity::getGoodsId, goodsId)
                .list();
        if (goodsToActivityEntities != null && !goodsToActivityEntities.isEmpty()) {
            activityId = goodsToActivityEntities.get(0).getActivityId();
            if (StringUtils.isBlank(activityId)) {
                throw new BusinessException("非活动商品！");
//                throw new BusinessException("获取活动信息出错，请联系管理员！");
            }
        }

        boolean isActivity = StringUtils.isNotBlank(activityId);
        ActivityStatusResult activityStatus = null;
        if (isActivity) {
            activityStatus = activityService.getActivityStatus(activityId, goodsId);
        }

        MallOrderEntity orderInfo = new MallOrderEntity();
        orderInfo.setActivityId(activityId);
        // 判断限购
        synchronized (loginUser.getId().intern()) {

            if (entity.getIsLimited() != null && entity.getIsLimited() > 0) {
                // 限购判断
                MallUserCardEntity userCardEntity = new MallUserCardEntity();
                userCardEntity.setUserId(loginUser.getId());
                if (isActivity) {
                    // 本次活动的开始时间
                    userCardEntity.setAddTime(DateUtils.strToDate(activityStatus.getDate()[0].toString()));
                    // 微信优惠标识不一样 限购也不一样
                    userCardEntity.setCouponTag(entity.getGoodsTag());
                    // 本次活动的ID
                    userCardEntity.setActivityId(orderInfo.getActivityId());
                } else {
                    userCardEntity.setAddTime(DateUtils.addDateDays(new Date(), -1));
                    // 商品ID
                    userCardEntity.setGoodsIds(Collections.singletonList(entity.getId()));
                }
                MallOrderEntity orderGoodsEntity = orderGoodsService.queryUserRecord(userCardEntity);
                if (orderGoodsEntity != null && orderGoodsEntity.getNumber() != null && orderGoodsEntity.getNumber() + number > entity.getIsLimited()) {
                    if (isActivity) {
                        if (orderGoodsEntity.getOrderStatus().equals(Constant.OrderStatus.DFK.getValue())) {
                            return RestResponse.error(901, "当前存在一次订单未支付，请完成待支付订单！");
                        }
                        Map<String, String> map = null;

                        try {
                            map = JSONObject.parseObject(sysConfigService.getValue("GOODS_TAG_DESC"), HashMap.class);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (map != null && StringUtils.isNotBlank(map.get(entity.getGoodsTag()))) {
                            throw new BusinessException("非常抱歉，" + map.get(entity.getGoodsTag()) + "购买名额您已用完");
                        }
                        throw new BusinessException("非常抱歉，" + activityStatus.getExtend1() + "购买名额您已用完");
                    } else {
                        throw new BusinessException("每个用户限制购买" + entity.getIsLimited());
                    }
                }
            }

            if (isActivity) {
                if (!activityStatus.getIsStart()) {
                    return RestResponse.error("不在活动时间！");
                }
                switch (activityEntity.getWhitelistType()) {
                    case 6:
                    case 9:
                        MallUserActivityMobileEntity UserActivityMobile = userActivityMobileService.lambdaQuery()
                                .eq(MallUserActivityMobileEntity::getActivity, activityId)
                                .eq(MallUserActivityMobileEntity::getUserId, loginUser.getId())
                                .one();
                        if (org.apache.commons.lang3.ObjectUtils.anyNotNull(UserActivityMobile)
                                && StringUtils.isNotBlank(UserActivityMobile.getMobile())) {
                            mobile = UserActivityMobile.getMobile();
                        }
                        break;
                    default:
                        mobile = loginUser.getMobile();
                        break;
                }
                check(activityEntity, mobile);
//                mobile = UserActivityMobile.getMobile();
                // redis库存扣减
                activityService.getActivityDetails(activityId, null);

                if (jedisUtil.hincrBy(Constant.ACTIVITY_DETAILS_STOCK + activityId, activityStatus.getGoodsToActivityId(), -number.longValue()) < 0) {
                    // 数量置0  使其不出现负数
                    jedisUtil.hincrBy(Constant.ACTIVITY_DETAILS_STOCK + activityId, activityStatus.getGoodsToActivityId(), number.longValue());
                    return RestResponse.error("已经被抢完啦！下次再来吧");
                }
                // 减活动配置库存
                if (!goodsToActivityService.lambdaUpdate().setSql("expend_count = expend_count - " + number)
                        .eq(MallGoodsToActivityEntity::getId, activityStatus.getGoodsToActivityId()).ge(MallGoodsToActivityEntity::getExpendCount, number)
                        .update()) {
                    return RestResponse.error("已经被抢完啦！下次再来吧");
                }
            }
            List<MallOrderGoodsEntity> orderGoodsData = new ArrayList<>();

//            LlProductSetMealEntity setMealEntity = null;
//            Boolean isLLShops = entity.getThirdSysNumber().equals(MallGoodsEntity.SysNumber.LL.getValue());
            boolean isCard = Optional.ofNullable(entity.getGoodsType()).orElse(0) == 1;
            // 设置默认的手机号
            orderInfo.setMobile(mobile);
//            orderInfo.setMobile(loginUser.getMobile());
            if (null == entity.getGoodsNumber() || entity.getGoodsNumber() < number) {
                return RestResponse.error("已经被抢完啦！下次再来吧！");
            }
            // 减商品库存
            if (!goodsService.lambdaUpdate().setSql("GOODS_NUMBER = GOODS_NUMBER - " + number)
                    .eq(MallGoodsEntity::getId, goodsId)
                    .ge(MallGoodsEntity::getGoodsNumber, number)
                    .update()) {
                throw new BusinessException("已经被抢完啦！下次再来吧！");
            }
            // 判断卡券密钥库存
            if (isCard) {
                orderInfo.setOrderType(Constant.CARD_ORDER);
                if (snService.count(new QueryWrapper<MallCardSnEntity>().eq("goods_Id", entity.getId()).eq("status", "0")) < number) {
                    throw new BusinessException("已经被抢完啦！下次再来吧！");
                }
            }
            try {
                // 获取要购买的商品和总价
                List<MallCartEntity> checkedGoodsList = new ArrayList<>();
                BigDecimal goodsTotalPrice;
                MallCartEntity cartVo = new MallCartEntity();
                goodsTotalPrice = entity.getRetailPrice().multiply(BigDecimal.valueOf(number));
                cartVo.setRetailPrice(entity.getRetailPrice());
                cartVo.setGoodsName(entity.getName());
                cartVo.setNumber(number);
                cartVo.setGoodsId(entity.getId());
                cartVo.setListPicUrl(entity.getListPicUrl());
                cartVo.setSkuId(skuId);
                cartVo.setGoodsSn(entity.getGoodsSn());
                cartVo.setGoodsEntity(entity);
                checkedGoodsList.add(cartVo);
                BigDecimal shippingFee = BigDecimal.valueOf(0);
                String orderSn = StringUtils.generateOrderNumber();
                // 优惠金额
                BigDecimal subPrice = new BigDecimal(0);
                //订单价格计算//订单的总价
                BigDecimal orderTotalPrice = goodsTotalPrice.add(shippingFee);
                BigDecimal actualPrice = orderTotalPrice.subtract(subPrice);
                orderInfo.setId(orderSn);
                orderInfo.setOrderSn(orderSn);
                orderInfo.setUserId(loginUser.getId());
                orderInfo.setCouponPrice(subPrice);
                orderInfo.setShopsId(shopsId);
                orderInfo.setFromType(fromType);
                //留言
                orderInfo.setPostscript(postscript);
                orderInfo.setAddTime(new Date());
                orderInfo.setExpireTime(DateUtils.addDateMinutes(new Date(), Integer.parseInt(sysConfigService.getValue(Constant.ORDER_EXPIRE, "30"))));
                if (actualPrice.compareTo(new BigDecimal(0)) <= 0) {
                    return RestResponse.error("订单金额不能为负或者等于0");
                }
                orderInfo.setActualPrice(actualPrice);
                orderInfo.setOrderPrice(orderTotalPrice);
                // 待付款
                orderInfo.setOrderStatus(Constant.OrderStatus.DFK.getValue());
                orderInfo.setShippingStatus(Constant.ShippingStatus.WFH.getValue());
                orderInfo.setPayStatus(Constant.PayStatus.WFK.getValue());
                orderInfo.setShippingFee(shippingFee);
                orderInfo.setIntegralMoney(new BigDecimal(0));
                //              log.info("商品信息：", entity);
                orderInfo.setActivityType(StringUtils.isBlank(entity.getGoodsTag()) ? (activityStatus == null ? "" : activityStatus.getActivityTag()) : entity.getGoodsTag());
                //插入订单信息和订单商品
                //验证验证码
//                MallActivityEntity activityEntity = activityService.getById(activityId);
                orderService.save(orderInfo);
                if (null == orderInfo.getId()) {
                    return RestResponse.error("订单提交失败！");
                }
                for (MallCartEntity goodsItem : checkedGoodsList) {
                    MallOrderGoodsEntity orderGoodsVo = new MallOrderGoodsEntity();
                    orderGoodsVo.setOrderId(orderInfo.getId());
                    orderGoodsVo.setGoodsId(goodsItem.getGoodsId());
                    orderGoodsVo.setGoodsSn(goodsItem.getGoodsSn());
                    orderGoodsVo.setSkuId(goodsItem.getSkuId());
                    orderGoodsVo.setGoodsName(goodsItem.getGoodsName());
                    orderGoodsVo.setListPicUrl(goodsItem.getListPicUrl());
                    orderGoodsVo.setMarketPrice(goodsItem.getMarketPrice());
                    orderGoodsVo.setRetailPrice(goodsItem.getRetailPrice());
                    orderGoodsVo.setNumber(goodsItem.getNumber());
                    // 设置微信优惠标识
                    orderGoodsVo.setCouponTag(goodsItem.getGoodsEntity().getGoodsTag());
                    orderGoodsVo.setGoodsSpecifitionNameValue(goodsItem.getGoodsSpecifitionNameValue());
                    orderGoodsData.add(orderGoodsVo);
                }
                orderGoodsService.saveBatch(orderGoodsData);
            } catch (Exception e) {
                if (isActivity) {
                    // redis 库存回退
                    jedisUtil.hincrBy(Constant.ACTIVITY_DETAILS_STOCK + activityId, activityStatus.getGoodsToActivityId(), number.longValue());
                }
                e.printStackTrace();
                throw new BusinessException(e.getMessage());
            }


            orderInfo.setOrderGoodsEntityList(orderGoodsData);
        }

        try {
            if (fromType.equals(Constant.FromType.MA.getValue())) {
                // 微信通知
//                sendMsgService.notifyPaySuccess(orderInfo, 0);
            } else if (orderInfo.getFromType().equals(Constant.FromType.MP.getValue())) {
                //TODO 公众号下单，发送消息
            } else if (orderInfo.getFromType().equals(Constant.FromType.MA.getValue())) {
                //TODO 小程序下单，发送消息
            } else if (orderInfo.getFromType().equals(Constant.FromType.QQ.getValue())) {
                //TODO QQ小程序下单，发送消息
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return RestResponse.success().put("data", orderInfo);
    }


    public void check(MallActivityEntity activity, String mobile) {

        String isMd5 = configService.getValue("WHITELIST_MD5");
        if (StringUtils.isNotBlank(mobile)) {
//            String mobile = entity.getMobile();
            MallWhitelistEntity whitelistEntity;
            switch (activity.getWhitelistType()) {
                case 1:
                    whitelistEntity = whitelistService.getOne(new LambdaQueryWrapper<MallWhitelistEntity>()
                            .eq(MallWhitelistEntity::getValid, Constant.ONE)
                            .eq(MallWhitelistEntity::getPhone, Constant.STR_ONE.equals(isMd5) ? Md5Utils.encrypt(mobile) : mobile)
                            .eq(MallWhitelistEntity::getType, activity.getWhitelistType())
                            .last("LIMIT 1"));
                    if (whitelistEntity == null) {
                        throw new BusinessException("非常抱歉，您暂不符合购买资格！");
                    }
                    break;
                case 3:
                    whitelistEntity = whitelistService.getOne(new LambdaQueryWrapper<MallWhitelistEntity>()
                            .eq(MallWhitelistEntity::getValid, Constant.ONE)
                            .eq(MallWhitelistEntity::getPhone, Constant.STR_ONE.equals(isMd5) ? Md5Utils.encrypt(mobile) : mobile)
                            .eq(MallWhitelistEntity::getType, activity.getWhitelistType())
                            .last("AND DATE_FORMAT(add_time,\"%Y-%m\") = DATE_FORMAT(now(),\"%Y-%m\") LIMIT 1"));
                    if (!org.apache.commons.lang3.ObjectUtils.anyNotNull(whitelistEntity)) {
                        throw new BusinessException("非常抱歉，您暂不符合购买资格！");
                    }
                    break;
                default:
                    whitelistEntity = whitelistService.getOne(new LambdaQueryWrapper<MallWhitelistEntity>()
                            .eq(MallWhitelistEntity::getValid, Constant.ONE)
                            .eq(MallWhitelistEntity::getPhone, Constant.STR_ONE.equals(isMd5) ? Md5Utils.encrypt(mobile) : mobile)
                            .eq(MallWhitelistEntity::getType, activity.getWhitelistType())
                            .last("LIMIT 1"));
                    if (!org.apache.commons.lang3.ObjectUtils.anyNotNull(whitelistEntity)) {
                        throw new BusinessException("非常抱歉，您暂不符合购买资格！");
                    }
                    break;
            }
        } else {
            throw new BusinessException("请绑定手机号！", 412);
        }

        switch (activity.getWhitelistType()) {
            case 1: //激活有礼
                List<MallOrderEntity> list = orderService.lambdaQuery().eq(MallOrderEntity::getActivityId, activity.getId())
                        .eq(MallOrderEntity::getPayStatus, Constant.PayStatus.YFK.getValue()).eq(MallOrderEntity::getMobile, mobile).list();
                if (list != null && list.size() >= 1) {
                    throw new BusinessException("您已购买！");
                }
                List<MallOrderEntity> list2 = orderService.lambdaQuery().eq(MallOrderEntity::getActivityId, activity.getId())
                        .eq(MallOrderEntity::getOrderStatus, Constant.OrderStatus.DFK).eq(MallOrderEntity::getMobile, mobile).list();
                if (list2 != null && list2.size() >= 1) {
                    throw new BusinessException("当前存在一次订单未支付，请完成待支付订单！");
                }
                break;
            case 3: //达标有礼
                List<MallOrderEntity> orderList = orderService.lambdaQuery().eq(MallOrderEntity::getActivityId, activity.getId())
                        .eq(MallOrderEntity::getPayStatus, Constant.PayStatus.YFK.getValue()).eq(MallOrderEntity::getMobile, mobile)
                        .last("AND DATE_FORMAT(add_time,\"%Y-%m\") = DATE_FORMAT(now(),\"%Y-%m\")")
                        .list();
                List<MallOrderEntity> orderList1 = orderService.lambdaQuery().eq(MallOrderEntity::getActivityId, activity.getId())
                        .eq(MallOrderEntity::getOrderStatus, Constant.OrderStatus.DFK).eq(MallOrderEntity::getMobile, mobile)
                        .last("AND DATE_FORMAT(add_time,\"%Y-%m\") = DATE_FORMAT(now(),\"%Y-%m\")")
                        .list();
                Integer shoppingCount = orderList.size() + orderList1.size();
                if (org.apache.commons.lang3.ObjectUtils.allNotNull(orderList1) && orderList1.size() > 0) {
                    throw new BusinessException("当前存在一次订单未支付，请完成待支付订单!", 901);
                }
                if (shoppingCount != null && shoppingCount >= 2) {
                    throw new BusinessException("您本月购买次数已经用完,每月限购买2次");
                }
                break;
            default:
                JSONObject activityDate = getActivityDate(activity);
                if (org.apache.commons.lang3.ObjectUtils.allNotNull(activityDate.getDate("startTime"))) {
                    List<MallOrderEntity> orderListY = orderService.lambdaQuery()
                            .eq(MallOrderEntity::getActivityId, activity.getId())
                            .eq(MallOrderEntity::getPayStatus, Constant.PayStatus.YFK.getValue())
                            .eq(MallOrderEntity::getMobile, mobile)
                            .between(MallOrderEntity::getAddTime,
                                    activityDate.getDate("startTime"),
                                    activityDate.getDate("endTime"))
                            .list();
                    List<MallOrderEntity> orderListD = orderService.lambdaQuery().eq(MallOrderEntity::getActivityId, activity.getId())
                            .eq(MallOrderEntity::getOrderStatus, Constant.OrderStatus.DFK.getValue()).eq(MallOrderEntity::getMobile, mobile)
                            .between(MallOrderEntity::getAddTime, activityDate.getDate("startTime"), activityDate.getDate("endTime"))
                            .list();
                    if (org.apache.commons.lang3.ObjectUtils.allNotNull(orderListD) && orderListD.size() > 0) {
                        throw new BusinessException("当前存在一次订单未支付，请完成待支付订单!", 901);
                    }
                    Integer shoppingCountD = orderListY.size() + orderListD.size();
                    int count = NumberUtils.toInt(sysConfigService.getValue(Constant.ACTIVITY_ORDER_COUNT, "1"));
                    if (shoppingCountD != null && shoppingCountD >= count) {
                        throw new BusinessException("您本次活动的购买次数已经用完,每个活动期间限购买" + count + "次!");
                    }
                } else {
                    throw new BusinessException("活动未开启，敬请期待！");
                }
                break;
        }
    }

    JSONObject getActivityDate(MallActivityEntity activity) {
        Map<String, Object> dateMap = new HashMap<>();
        LocalDate[][] dates = JSONObject.parseObject(activity.getActivityDate(), LocalDate[][].class);
        final LocalDate now = LocalDate.now();
        LocalDate[] date = null;
        int index = 0;
        for (int i = 0; i < dates.length; i++) {
            LocalDate[] item = dates[i];
            if (now.compareTo(item[0]) >= 0 && now.compareTo(item[1]) <= 0) {
                // 符合条件
                date = item;
                break;
            }
        }
        java.time.LocalTime[][] times = JSONObject.parseObject(activity.getActivityTime(), java.time.LocalTime[][].class);
        LocalTime nowTime = LocalTime.now();
        LocalTime[] time = null;
        for (int i = 0; i < times.length; i++) {
            java.time.LocalTime[] item = times[i];
            if (nowTime.compareTo(item[0]) >= 0 && nowTime.compareTo(item[1]) <= 0) {
                time = item;
                break;
            }
        }
        // 未找到符合条件的活动时间，则寻找最接近当前的时间
        if (date == null) {
            date = dates[index];
            // activitFlag  -1 已经结束   1 进行中  2 未开始
            if (now.compareTo(date[1]) > 0) {
                activity.setBuyStatus(2);//已结束
            } else {
                activity.setBuyStatus(-1);//未开始
            }
        } else {
            if (time == null) {
                time = times[index];
                if (nowTime.compareTo(time[1]) > 0) {
                    activity.setBuyStatus(-1);//未开始
                } else {
                    activity.setBuyStatus(0);//即将开始
                }
            } else {
                LocalDateTime localStart = LocalDateTime.parse(date[0] + "T" + time[0]);
                LocalDateTime localEnd = LocalDateTime.parse(date[1] + "T" + time[1]);
                dateMap.put("startTime", Date.from(localStart.atZone(ZoneId.systemDefault()).toInstant()));
                dateMap.put("endTime", Date.from(localEnd.atZone(ZoneId.systemDefault()).toInstant()));
                activity.setBuyStatus(1);//已经开始
            }
        }
        String jsonStr = JSONObject.toJSONString(dateMap);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        return jsonObject;
    }

    @Autowired
    private GoShoppingService goShoppingService;

    @PostMapping("submitOrder")
    @ApiOperation(value = "提交订单2", notes = "购买一个商品，需要活动id")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "token", value = "用户token", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "body", name = "jsonParam", value = "JSON格式参数", examples = @Example({
                    @ExampleProperty(mediaType = "fromType", value = "用户下单来源类型 1:微信小程序 2:微信公众号 3:app 4:H5 5:支付宝小程序 6:QQ小程序"),
                    @ExampleProperty(mediaType = "goodsId", value = "商品id"),
                    @ExampleProperty(mediaType = "shopsId", value = "商户id"),
                    @ExampleProperty(mediaType = "number", value = "购买数量"),
                    @ExampleProperty(mediaType = "phone", value = "手机"),
                    @ExampleProperty(mediaType = "uname", value = "姓名"),
                    @ExampleProperty(mediaType = "postscript", value = "留言")
            }), required = true, dataType = "string")
    })
    public RestResponse submitOrder(@LoginUser MallUserEntity loginUser, @RequestBody JSONObject jsonParam) {

        int number = jsonParam.getIntValue("number");
        String goodsId = jsonParam.getString("goodsId");
        String shopsId = jsonParam.getString("shopsId");
        int fromType = jsonParam.getIntValue("fromType");
        String postscript = jsonParam.getString("postscript");
        String phone = jsonParam.getString("phone");
        String uname = jsonParam.getString("uname");

        DirectGoShoppingBo bo = new DirectGoShoppingBo();
        bo.setUserId(loginUser.getId());
        bo.setMobile(phone);
        bo.setGoodsId(goodsId);
        bo.setNumber(number);
        bo.setFromType(fromType);
        bo.setPostscript(postscript);
        bo.setShopsId(shopsId);
        bo.setUname(uname);

        MallOrderEntity order = goShoppingService.directPayOfGoods(bo);
        if (order != null) {
            return RestResponse.success().put("data", order);
        }
        return RestResponse.error("操作错误，请重试");
    }

}
